<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">


<meta name="google-site-verification" content="E9deYnivN5MuHMuIfiMZZfS0alv-d_0UjcwjBL79lGU" />



<meta name="baidu-site-verification" content="iHYWJxscwD" />










<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />








  <meta name="baidu-site-verification" content="true" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="学习笔记,量化投资,机器学习,回归分析,Backtrader,多因子选股," />










<meta name="description" content="接着上次的程序，我想到用机器学习算法来进行多因子选股的方法。之前的程序是先假设因子之间是线性关系，然后求方程的系数。现在我考虑能不能将每个候选股票的各个因子的值，以及每个股票的年化收益率直接当做数据”喂给”算法，看看能有啥结果。首先造数据吧。因子数据的获取跟筛选和之前是一样的。 12345678910111213141516171819# 获取股票数据，进行初步筛选，返回供因子分析的股票数据。de">
<meta property="og:type" content="article">
<meta property="og:title" content="量化投资学习笔记87——实现量化交易经典策略:多因子选股（改进2）">
<meta property="og:url" content="https://zwdnet.github.io/2020/09/04/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B087%E2%80%94%E2%80%94%E5%AE%9E%E7%8E%B0%E9%87%8F%E5%8C%96%E4%BA%A4%E6%98%93%E7%BB%8F%E5%85%B8%E7%AD%96%E7%95%A5-%E5%A4%9A%E5%9B%A0%E5%AD%90%E9%80%89%E8%82%A1%EF%BC%88%E6%94%B9%E8%BF%9B2%EF%BC%89/index.html">
<meta property="og:site_name" content="赵瑜敏的口腔医学专业学习博客">
<meta property="og:description" content="接着上次的程序，我想到用机器学习算法来进行多因子选股的方法。之前的程序是先假设因子之间是线性关系，然后求方程的系数。现在我考虑能不能将每个候选股票的各个因子的值，以及每个股票的年化收益率直接当做数据”喂给”算法，看看能有啥结果。首先造数据吧。因子数据的获取跟筛选和之前是一样的。 12345678910111213141516171819# 获取股票数据，进行初步筛选，返回供因子分析的股票数据。de">
<meta property="og:locale">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/60/01.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/60/02.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/60/03.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/60/04.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/60/05.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/60/06.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/60/07.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/60/08.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/60/09.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/60/10.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg">
<meta property="article:published_time" content="2020-09-04T05:49:46.000Z">
<meta property="article:modified_time" content="2020-09-27T06:13:25.000Z">
<meta property="article:author" content="赵瑜敏">
<meta property="article:tag" content="学习笔记">
<meta property="article:tag" content="量化投资">
<meta property="article:tag" content="机器学习">
<meta property="article:tag" content="回归分析">
<meta property="article:tag" content="Backtrader">
<meta property="article:tag" content="多因子选股">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/60/01.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zwdnet.github.io/2020/09/04/量化投资学习笔记87——实现量化交易经典策略-多因子选股（改进2）/"/>





  <title>量化投资学习笔记87——实现量化交易经典策略:多因子选股（改进2） | 赵瑜敏的口腔医学专业学习博客</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">赵瑜敏的口腔医学专业学习博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zwdnet.github.io/2020/09/04/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B087%E2%80%94%E2%80%94%E5%AE%9E%E7%8E%B0%E9%87%8F%E5%8C%96%E4%BA%A4%E6%98%93%E7%BB%8F%E5%85%B8%E7%AD%96%E7%95%A5-%E5%A4%9A%E5%9B%A0%E5%AD%90%E9%80%89%E8%82%A1%EF%BC%88%E6%94%B9%E8%BF%9B2%EF%BC%89/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="赵瑜敏的口腔医学专业学习博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">量化投资学习笔记87——实现量化交易经典策略:多因子选股（改进2）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-09-04T05:49:46+00:00">
                2020-09-04
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" itemprop="url" rel="index">
                    <span itemprop="name">量化投资</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                  <span class="post-meta-divider">|</span>
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.3k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  5
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>接着上次的程序，我想到用机器学习算法来进行多因子选股的方法。之前的程序是先假设因子之间是线性关系，然后求方程的系数。现在我考虑能不能将每个候选股票的各个因子的值，以及每个股票的年化收益率直接当做数据”喂给”算法，看看能有啥结果。<br>首先造数据吧。<br>因子数据的获取跟筛选和之前是一样的。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 获取股票数据，进行初步筛选，返回供因子分析的股票数据。</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">getFactors</span>():</span></span><br><span class="line"><span class="comment">#    data = ts.get_stock_basics()</span></span><br><span class="line"><span class="comment">#    print(data.head())</span></span><br><span class="line"><span class="comment">#    print(len(data))</span></span><br><span class="line"><span class="comment">#    data.to_csv(&quot;stocks.csv&quot;)</span></span><br><span class="line">    data = pd.read_csv(<span class="string">&quot;stocks.csv&quot;</span>, index_col = <span class="string">&quot;code&quot;</span>)</span><br><span class="line">    <span class="comment"># 排除亏损的股票</span></span><br><span class="line">    data = data[data.npr &gt; <span class="number">0.0</span>]</span><br><span class="line">    <span class="comment"># 排除上市不满2年的</span></span><br><span class="line">    data = data[data.timeToMarket &lt;= <span class="number">20180801</span>]</span><br><span class="line">    <span class="comment"># 排除ST股票</span></span><br><span class="line">    data = data[~ data.name.<span class="built_in">str</span>.contains(<span class="string">&quot;ST&quot;</span>)]</span><br><span class="line">    <span class="comment"># 排除代码小于100000的股票</span></span><br><span class="line">    data = data[data.index &gt;= <span class="number">100000</span>]</span><br><span class="line">    <span class="comment"># 排除退市的股票</span></span><br><span class="line">    data = data[data.pe != <span class="number">0</span>]</span><br><span class="line">    <span class="comment"># print(data)</span></span><br><span class="line">    <span class="keyword">return</span> data</span><br></pre></td></tr></table></figure>
<p>接下来，要对每只股票在回测时间范围内回测出其年化收益率。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 对所有股票回测其年化收益率</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">getReturn</span>(<span class="params">data</span>):</span></span><br><span class="line">    <span class="keyword">if</span> os.path.exists(<span class="string">&quot;data.csv&quot;</span>):</span><br><span class="line">        data = pd.read_csv(<span class="string">&quot;data.csv&quot;</span>, index_col = <span class="string">&quot;code&quot;</span>)</span><br><span class="line">        <span class="keyword">return</span> data</span><br><span class="line">    start = <span class="string">&quot;2017-01-01&quot;</span></span><br><span class="line">    end = <span class="string">&quot;2020-07-31&quot;</span></span><br><span class="line">    codes = data.index</span><br><span class="line">    names = fromCodeToName(data, codes)</span><br><span class="line">    codes = [<span class="built_in">str</span>(x) <span class="keyword">for</span> x <span class="keyword">in</span> codes]</span><br><span class="line"><span class="comment">#    print(codes)</span></span><br><span class="line"><span class="comment">#    print(names)</span></span><br><span class="line">    <span class="comment"># 在数据中增加一列计算年化收益率</span></span><br><span class="line">    data[<span class="string">&quot;ar&quot;</span>] = <span class="number">0.0</span></span><br><span class="line">    t = <span class="number">0</span></span><br><span class="line">    cash = <span class="number">100000</span></span><br><span class="line">    <span class="keyword">for</span> code <span class="keyword">in</span> data.index:</span><br><span class="line">        test = backtest.BackTest(FactorStrategy, start, end, [<span class="built_in">str</span>(code)], [names[t]], cash, bDraw = <span class="literal">False</span>)</span><br><span class="line">        result = test.run()</span><br><span class="line">        print(<span class="string">&quot;第&#123;&#125;次回测，股票代码&#123;&#125;，回测年化收益率&#123;&#125;。&quot;</span>.<span class="built_in">format</span>(t+<span class="number">1</span>, code, result.年化收益率))</span><br><span class="line">        data.loc[code, [<span class="string">&quot;ar&quot;</span>]] = result.年化收益率</span><br><span class="line">        t += <span class="number">1</span></span><br><span class="line">    data.to_csv(<span class="string">&quot;data.csv&quot;</span>)</span><br><span class="line">    <span class="keyword">return</span> data</span><br></pre></td></tr></table></figure>
<p>只用回测一次，保存到文件里，下次直接读取。<br>现在数据有了，开始分析吧。<br>先看看数据情况:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">print(data.info())</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/60/01.png"><br>先看看年化收益率的分布情况。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/60/02.png"><br>下面用pairplot将所有变量两两配对画图看看。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/60/03.png"><br>先用线性回归，把所有变量放进去，以年化收益率为因变量，看看回归结果。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 多元线性回归</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">multiRegress</span>(<span class="params">data</span>):</span></span><br><span class="line">    x = data.iloc[:, <span class="number">3</span>:<span class="number">21</span>]</span><br><span class="line">    y = data.iloc[:, <span class="number">22</span>]</span><br><span class="line">    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = <span class="number">0.2</span>, random_state = <span class="number">631</span>)</span><br><span class="line">    line_reg = LinearRegression()</span><br><span class="line">    model = line_reg.fit(x_train, y_train)</span><br><span class="line">    print(<span class="string">&quot;模型参数:&quot;</span>, model)</span><br><span class="line">    print(<span class="string">&quot;模型截距:&quot;</span>, model.intercept_)</span><br><span class="line">    print(<span class="string">&quot;参数权重:&quot;</span>, model.coef_)</span><br><span class="line">    </span><br><span class="line">    y_pred = line_reg.predict(x_test)</span><br><span class="line">    sum_mean = <span class="number">0</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(y_pred)):</span><br><span class="line">        sum_mean += (y_pred[i] - y_test.values[i]) ** <span class="number">2</span></span><br><span class="line">    sum_erro = np.sqrt(sum_mean /<span class="built_in">len</span>(y_pred))</span><br><span class="line">    print(<span class="string">&quot;RMSR=&quot;</span>, sum_erro)</span><br><span class="line">    print(<span class="string">&quot;Score=&quot;</span>, model.score(x_test, y_test))</span><br><span class="line">    <span class="comment"># ROC曲线</span></span><br><span class="line">    plt.figure()</span><br><span class="line">    plt.plot(<span class="built_in">range</span>(<span class="built_in">len</span>(y_pred)), y_pred, <span class="string">&#x27;b&#x27;</span>, label=<span class="string">&quot;predict&quot;</span>)</span><br><span class="line">    plt.plot(<span class="built_in">range</span>(<span class="built_in">len</span>(y_pred)), y_test, <span class="string">&#x27;r&#x27;</span>, label=<span class="string">&quot;test&quot;</span>)</span><br><span class="line">    plt.legend(loc=<span class="string">&quot;upper right&quot;</span>) </span><br><span class="line">    <span class="comment"># 显示图中的标签</span></span><br><span class="line">    plt.xlabel(<span class="string">&quot;facts&quot;</span>)</span><br><span class="line">    plt.ylabel(<span class="string">&#x27;ar&#x27;</span>)</span><br><span class="line">    plt.savefig(<span class="string">&quot;line_regress_result.png&quot;</span>)</span><br><span class="line">    plt.close()</span><br><span class="line">    <span class="comment"># 保存模型</span></span><br><span class="line">    joblib.dump(model, <span class="string">&quot;LineRegress.m&quot;</span>)</span><br><span class="line">    <span class="keyword">return</span> mode</span><br></pre></td></tr></table></figure>
<p>回归结果</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">模型参数: LinearRegression(copy_X=<span class="literal">True</span>, fit_intercept=<span class="literal">True</span>, n_jobs=<span class="number">1</span>, normalize=<span class="literal">False</span>)                              模型截距: -<span class="number">0.018973640684523358</span>                参数权重: [-<span class="number">1.56402370e-06</span>  <span class="number">1.74669993e-07</span>  <span class="number">6.98664492e-07</span> -<span class="number">4.44613478e-08</span>  <span class="number">5.43375427e-07</span>  <span class="number">3.22291009e-06</span>  <span class="number">2.06702726e-05</span>  <span class="number">5.75364273e-03</span>  <span class="number">6.13467186e-03</span> -<span class="number">3.06546497e-03</span> <span class="number">3.31053106e-03</span>  <span class="number">5.14874613e-10</span>              <span class="number">1.80572770e-07</span>  <span class="number">3.25824964e-03</span>  <span class="number">4.28603067e-05</span>  <span class="number">8.08821164e-07</span>                  <span class="number">1.29863432e-04</span>  <span class="number">5.30351262e-06</span>]                          </span><br><span class="line">RMSR= <span class="number">0.019172719955231714</span>                    Score= <span class="number">0.4389434373773129</span></span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/60/04.png"><br>用回归结果的预测值排序取前十的股票作为组合中的股票，回测10年的结果看看。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 测试多元线性回归的效果</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">testMultiRegress</span>(<span class="params">data</span>):</span></span><br><span class="line">    model = joblib.load(<span class="string">&quot;LineRegress.m&quot;</span>)</span><br><span class="line">    pred_return = model.predict(data.iloc[:, <span class="number">3</span>:<span class="number">21</span>])</span><br><span class="line">    <span class="comment"># print(pred_return)</span></span><br><span class="line">    data[<span class="string">&quot;pred_ar&quot;</span>] = pred_return</span><br><span class="line">    <span class="comment"># print(data)</span></span><br><span class="line">    <span class="comment"># 排序</span></span><br><span class="line">    data = data.sort_values(by = <span class="string">&quot;pred_ar&quot;</span>, ascending = <span class="literal">False</span>)</span><br><span class="line">    <span class="comment"># print(data)</span></span><br><span class="line">    <span class="comment"># 取前十个股票作为投资标的</span></span><br><span class="line">    codes = data.index[<span class="number">0</span>:<span class="number">10</span>].values</span><br><span class="line">    <span class="comment"># print(codes)</span></span><br><span class="line">    names = fromCodeToName(data, codes)</span><br><span class="line">    codes = [<span class="built_in">str</span>(x) <span class="keyword">for</span> x <span class="keyword">in</span> codes]</span><br><span class="line">    start = <span class="string">&quot;2010-01-01&quot;</span></span><br><span class="line">    end = <span class="string">&quot;2020-07-01&quot;</span></span><br><span class="line">    cash = <span class="number">1000000</span></span><br><span class="line">    opttest = backtest.BackTest(FactorStrategy, start, end, codes, names, cash, bDraw = <span class="literal">True</span>)</span><br><span class="line">    result = opttest.run()</span><br><span class="line">    print(<span class="string">&quot;多元线性回归的回测结果:&quot;</span>)</span><br><span class="line">    print(result)</span><br></pre></td></tr></table></figure>
<p>回测结果<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/60/05.png"><br>年化收益率41.8%。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/60/06.png"><br>还不错，但还是有那个bug，我是用最近的因子数据算的，回测的数据却是用之前的数据。<br>再试一下别的机器学习算法。<br>多项式回归，代码不赘述了，直接放结果。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/60/07.png"><br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/60/08.png"><br>回归结果个别值相差很大，最后回测结果也差一些。不过年化仍然达到40%。<br>在写这篇笔记搜索的时候我才知道，原来随机森林和深度学习也可以做回归！试试吧。<br>先用回归随机森林，参考这里： <a target="_blank" rel="noopener" href="https://blog.csdn.net/GitzLiu/article/details/81952712">https://blog.csdn.net/GitzLiu/article/details/81952712</a><br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/60/09.png"></p>
<p>看着还不错，再用结果回测试试。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/60/10.png"></p>
<p>更好一些，年化到43.4%。<br>具体代码看： <a target="_blank" rel="noopener" href="https://github.com/zwdnet/MyQuant/tree/master/48">https://github.com/zwdnet/MyQuant/tree/master/48</a><br>策略文件为facts.py。<br>这次主要是回归算法。下次看分类算法。</p>
<p>我发文章的三个地方，欢迎大家在朋友圈等地方分享，欢迎点“在看”。<br>我的个人博客地址：<a href="https://zwdnet.github.io/">https://zwdnet.github.io</a><br>我的知乎文章地址： <a target="_blank" rel="noopener" href="https://www.zhihu.com/people/zhao-you-min/posts">https://www.zhihu.com/people/zhao-you-min/posts</a><br>我的微信个人订阅号：赵瑜敏的口腔医学学习园地</p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg"></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欢迎打赏！感谢支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/mm_facetoface_collect_qrcode_1542944836634.png" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/1542944857770.jpg" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" rel="tag"># 学习笔记</a>
          
            <a href="/tags/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" rel="tag"># 量化投资</a>
          
            <a href="/tags/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/" rel="tag"># 机器学习</a>
          
            <a href="/tags/%E5%9B%9E%E5%BD%92%E5%88%86%E6%9E%90/" rel="tag"># 回归分析</a>
          
            <a href="/tags/Backtrader/" rel="tag"># Backtrader</a>
          
            <a href="/tags/%E5%A4%9A%E5%9B%A0%E5%AD%90%E9%80%89%E8%82%A1/" rel="tag"># 多因子选股</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/08/30/%E6%A0%91%E8%84%82%E7%B2%98%E6%8E%A5%E5%BC%8F%E5%9B%BA%E5%AE%9A%E6%A1%A5%E7%9A%84%E6%9C%AF%E5%89%8D%E5%87%86%E5%A4%87%E5%92%8C%E4%B8%B4%E5%BA%8A%E6%B5%81%E7%A8%8B%E2%80%94%E2%80%94%E9%94%90%E8%AF%BB%E4%BC%9A%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B002/" rel="next" title="树脂粘接式固定桥的术前准备和临床流程——锐读会课程笔记02">
                <i class="fa fa-chevron-left"></i> 树脂粘接式固定桥的术前准备和临床流程——锐读会课程笔记02
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/09/05/%E6%A0%B9%E7%AE%A1%E7%96%8F%E9%80%9A%E5%92%8C%E5%8A%A8%E8%83%BD%E5%86%B2%E6%B4%97%E7%9A%84%E4%B8%B4%E5%BA%8A%E7%AD%96%E7%95%A5/" rel="prev" title="根管疏通和动能冲洗的临床策略">
                根管疏通和动能冲洗的临床策略 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTA2Mi8xNzU4Nw=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%20%7C%7C%20archive">
              
                  <span class="site-state-item-count">452</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">29</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">544</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">本站版权归赵瑜敏所有，如欲转载请与本人联系。</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">1225.8k</span>
  
</div>









<div>
  <script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1275447216'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s11.cnzz.com/z_stat.php%3Fid%3D1275447216%26online%3D1%26show%3Dline' type='text/javascript'%3E%3C/script%3E"));</script>
</div>

        







  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1275447216&web_id=1275447216" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

  
</body>
</html>
